package org.enwey.icarenew.Activity.Login;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.kbeanie.imagechooser.api.ChooserType;
import com.kbeanie.imagechooser.api.ChosenImage;
import com.kbeanie.imagechooser.api.ImageChooserListener;
import com.kbeanie.imagechooser.api.ImageChooserManager;

import org.enwey.icarenew.API.APIManager;
import org.enwey.icarenew.API.RequestResult;
import org.enwey.icarenew.APPUtils.DialogUtil;
import org.enwey.icarenew.APPUtils.StringUtil;
import org.enwey.icarenew.APPUtils.ToastUtil;
import org.enwey.icarenew.Activity.Base.BaseActivity;
import org.enwey.icarenew.Activity.Personal.UserInfoActivity;
import org.enwey.icarenew.Component.CircleImageView;
import org.enwey.icarenew.Constant;
import org.enwey.icarenew.Manager.SettingsManager;
import org.enwey.icarenew.Model.User;
import org.enwey.icarenew.R;

import java.util.Hashtable;

import eu.janmuller.android.simplecropimage.CropImage;


/**
 * Created by enwey on 2014/11/23.
 */
public class PerfectUserInfo extends BaseActivity implements ImageChooserListener {
    private final String TAG = "PerfectUserInfo";
    private RelativeLayout mSetHeader;
    private CircleImageView mUserHeadImg;
    private EditText mNick;
    private EditText mSummary;
    private TextView mSave;
    private String phoneNum;
    private User mLoginUser;
    private int mChooserType;
    private ImageChooserManager mImageChooserManager;
    private String mImageFilePath;
    private boolean isLoading;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_perfect);
        setUp();
        findView();
        initChooseTypeValue(savedInstanceState);
        registerListener();
    }

    private void setUp() {
        showLeftBtn();
        mLoginUser = SettingsManager.getLoginUser();
        if (mLoginUser != null) {

        }
    }

    private void findView() {
        mSetHeader = (RelativeLayout) this.findViewById(R.id.activity_perfect_set_header);
        mSave = (TextView) this.findViewById(R.id.activity_perfect_save_btn);
        mUserHeadImg = (CircleImageView) this.findViewById(R.id.activity_update_info_image);
        mNick = (EditText) this.findViewById(R.id.activity_perfect_user_nick);
        mSummary = (EditText) this.findViewById(R.id.activity_perfect_user_summary);
        if (isLogin()) {
            setTitle("修改资料");
            setUserData();
        } else {
            setTitle("完善资料");
            phoneNum = getIntent().getStringExtra("phone");
        }
        mUserHeadImg.setErrorImageResId(R.drawable.img_header_big);
        mUserHeadImg.setDefaultImageResId(R.drawable.img_header_big);
        mUserHeadImg.setImageUrl(APIManager.toAbsoluteUrl(StringUtil.showMessage(mLoginUser.avatar)),
                APIManager.getInstance(PerfectUserInfo.this).getImageLoader());
    }

    private void initChooseTypeValue(Bundle savedInstanceState) {
        if (savedInstanceState == null) {
            return;
        }
        int chooseType = savedInstanceState.getInt("chooseType", 12);
        String imageFilePath = savedInstanceState.getString("imageFilePath");
        if (!TextUtils.isEmpty(imageFilePath)) {
            mImageFilePath = imageFilePath;
        }
        if (chooseType != 12) {
            mChooserType = chooseType;
        }
    }

    private void registerListener() {
        View.OnClickListener register = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (v.getId() == R.id.activity_perfect_save_btn) {
                    doCompleteInfo();
                } else if (v.getId() == R.id.activity_perfect_set_header) {
                    setHeaderImage();
                }
            }
        };
        mSave.setOnClickListener(register);
        mSetHeader.setOnClickListener(register);
    }

    private boolean isLogin() {
        boolean flag = false;
        if (mLoginUser != null) {
            flag = true;
        }
        return flag;
    }

    private void setUserData() {
        phoneNum = mLoginUser.account;
        if (mLoginUser.nick != null) {
            mNick.setText(mLoginUser.nick + "");
        }

        if (mLoginUser.summary != null) {
            mSummary.setText(mLoginUser.summary + "");
        }
    }

    @Override
    public void showLoading() {
        isLoading = true;
        super.showProgressDialog(getApplication().getString(R.string.dialog_message_loading)).setCancelable(false);
    }

    @Override
    public void hideLoading() {
        isLoading = false;
        super.hideProgressDialog();
    }

    private void doCompleteInfo() {
        String nick = mNick.getText().toString().trim();
        String summary = mSummary.getText().toString().trim();

        if (TextUtils.isEmpty(nick)) {
            nick = "大懒虫";
        }

        if (TextUtils.isEmpty(summary)) {
            summary = "我很懒，什么都没有留下...";
        }

        if (TextUtils.isEmpty(phoneNum)) {
            ToastUtil.show(PerfectUserInfo.this, "登录异常,请重新登录");
            Intent intent = new Intent(PerfectUserInfo.this, LoginActivity.class);
            startActivity(intent);
            finish();
            return;
        }

        CallAPIUpdateInfo(nick, summary);

    }

    // find image to user header
    private void setHeaderImage() {
        DialogUtil.showTakePhotoDialog(PerfectUserInfo.this, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (which == 0) {
                    //take picture
                    mChooserType = ChooserType.REQUEST_CAPTURE_PICTURE;
                    mImageChooserManager = new ImageChooserManager(PerfectUserInfo.this,
                            ChooserType.REQUEST_CAPTURE_PICTURE,
                            Constant.PATH_IMAGE_TEMP_FOLDER,
                            true);
                    mImageChooserManager.setImageChooserListener(PerfectUserInfo.this);
                    try {
                        mImageFilePath = mImageChooserManager.choose();
                    } catch (IllegalArgumentException e) {
                        e.printStackTrace();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                } else {
                    //choose photo
                    mChooserType = ChooserType.REQUEST_PICK_PICTURE;
                    mImageChooserManager = new ImageChooserManager(PerfectUserInfo.this,
                            ChooserType.REQUEST_PICK_PICTURE,
                            Constant.PATH_IMAGE_TEMP_FOLDER,
                            true);
                    mImageChooserManager.setImageChooserListener(PerfectUserInfo.this);
                    try {
                        mImageFilePath = mImageChooserManager.choose();
                    } catch (IllegalArgumentException e) {
                        e.printStackTrace();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == ChooserType.REQUEST_CAPTURE_PICTURE
                    || requestCode == ChooserType.REQUEST_PICK_PICTURE) {
                // 选择图片或拍照的result
                if (mImageChooserManager == null) {
                    reinitializeImageChooser();
                }
                showProgressDialog();
                mImageChooserManager.submit(requestCode, data);
                hideProgressDialog();

            } else if (requestCode == Constant.CHOOSE_IMAGE_CROP_IMAGE_REQUEST_CODE) {
                // 裁剪图片的result
                if (data == null) {
                    return;
                }
                String path = data.getStringExtra(CropImage.IMAGE_PATH);
                if (path == null) {
                    return;
                }
                Bitmap bm = null;
                try {
                    bm = BitmapFactory.decodeFile(path);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                callAPIUpdateHead();

            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void reinitializeImageChooser() {
        mImageChooserManager = new ImageChooserManager(this, mChooserType, "imagefolder", true);
        mImageChooserManager.setImageChooserListener(this);
        mImageChooserManager.reinitialize(mImageFilePath);
    }

    private void CallAPIUpdateInfo(final String nick, final String summary) {
        showProgressDialog().setCancelable(false);
        Hashtable<String, String> parameters = new Hashtable<>();
        parameters.put("account", phoneNum);
        parameters.put("nick", nick);
        parameters.put("summary", summary);

        APIManager.getInstance(this).completeInfo(parameters, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                hideProgressDialog();
                showException(error);
            }
        }, new Response.Listener<RequestResult<User>>() {
            @Override
            public void onResponse(RequestResult<User> response) {
                hideProgressDialog();

                if (hasError(response)) {
                    return;
                }

                if (response != null && response.message != null) {
                    ToastUtil.show(PerfectUserInfo.this, response.message);
                    mLoginUser.nick = nick;
                    mLoginUser.summary = summary;
                    if (isLogin()) {
                        SettingsManager.deleteLoginUser();
                        SettingsManager.saveLoginUser(mLoginUser);
                        goToUserInfoActivity(PerfectUserInfo.this);
                    } else {
                        goToLoginActivity(PerfectUserInfo.this);
                    }
                }
            }
        });
    }

    private void callAPIUpdateHead() {
        isLoading = true;
        showProgressDialog(getApplication().getString(R.string.dialog_message_upload)).setCancelable(false);
        Hashtable<String, String> parameters = new Hashtable<>();
        parameters.put("user_id", mLoginUser.id+"");
        parameters.put("imgFile", mImageFilePath);
        APIManager.getInstance(this).updateHead(parameters,
                new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        PerfectUserInfo weakActivity = (PerfectUserInfo) weakThis.get();
                        if (weakActivity == null) {
                            return;
                        }
                        weakActivity.hideLoading();
                        weakActivity.showException(error);
                    }
                }, new Response.Listener<RequestResult<?>>() {

                    @Override
                    public void onResponse(RequestResult<?> response) {
                        PerfectUserInfo weakActivity = (PerfectUserInfo) weakThis.get();
                        if (weakActivity == null) {
                            return;
                        }
                        weakActivity.hideLoading();
                        if (weakActivity.hasError(response)) {
                            return;
                        }
                        try {
                            if (weakActivity.mLoginUser == null) {
                                weakActivity.mLoginUser = SettingsManager.getLoginUser();
                            }
                            weakActivity.mLoginUser.avatar = (String) response.data;
                            SettingsManager.saveLoginUser(weakActivity.mLoginUser);
                            if (weakActivity.mUserHeadImg != null) {
                                weakActivity.mUserHeadImg.setImageUrl(APIManager.toAbsoluteUrl(weakActivity.mLoginUser.avatar),
                                        APIManager.getInstance(weakActivity).getImageLoader());
                                ToastUtil.show(weakActivity, response.message);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    private void goToLoginActivity(PerfectUserInfo weakActivity) {
        Intent intent = new Intent();
        intent.setClass(weakActivity, LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("phone", phoneNum);
        startActivity(intent);
        finish();
    }

    private void goToUserInfoActivity(PerfectUserInfo weakActivity) {
        Intent intent = new Intent();
        intent.setClass(weakActivity, UserInfoActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
        finish();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("chooseType", mChooserType);
        outState.putString("imageFilePath", mImageFilePath);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        if (savedInstanceState == null) {
            return;
        }
        int chooseType = savedInstanceState.getInt("chooseType", 12);
        String imageFilePath = savedInstanceState.getString("imageFilePath");
        if (!TextUtils.isEmpty(imageFilePath)) {
            mImageFilePath = imageFilePath;
        }
        if (chooseType != 12) {
            mChooserType = chooseType;
        }
    }

    @Override
    public void onImageChosen(final ChosenImage image) {
        if (image != null) {
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    hideProgressDialog();
                    mImageFilePath = image.getFileThumbnail();
                    Intent intent = new Intent(PerfectUserInfo.this, CropImage.class);
                    intent.putExtra(CropImage.IMAGE_PATH, mImageFilePath);
                    intent.putExtra(CropImage.SCALE, true);

                    intent.putExtra(CropImage.ASPECT_X, 3);
                    intent.putExtra(CropImage.ASPECT_Y, 3);
                    intent.putExtra(CropImage.OUTPUT_X, 256);
                    intent.putExtra(CropImage.OUTPUT_Y, 256);
                    startActivityForResult(intent, Constant.CHOOSE_IMAGE_CROP_IMAGE_REQUEST_CODE);
                }
            });
        }
    }

    @Override
    public void onError(String reason) {
        runOnUiThread(new Runnable() {

            @Override
            public void run() {
                hideProgressDialog();
            }
        });
    }

}
